import { Router } from "vue-router"
import { store } from "@/store"

export function routerGuard(router: Router) {
    router.beforeEach(async (to, from, next) => {
        window.$loading.start()

        let auth = true

        if (to.meta && to.meta.hasOwnProperty("auth")) {
            if (!to.meta.auth) {
                auth = false
            }
        }

        if (auth) {
            if (store.state.userinfo.isLogin) {
                next()
            } else {
                const query: any = {}

                if (["/", "/home"].indexOf(to.path) < 0) {
                    query["origin"] = to.fullPath
                }

                next({
                    path: "/login",
                    query: query,
                })
            }
        } else {
            next()
        }
    })

    router.afterEach((to, from, failure) => {
        window.$loading.finish()
    })
}
